package sz.szsmk.citizencard.ui.newversion.fragment

import android.Manifest
import android.app.Service
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.Handler
import android.os.Vibrator
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import com.chenenyu.router.Router
import kotlinx.android.synthetic.main.fragment_buscode.*
import kotlinx.android.synthetic.main.layout_buscode_noenoughmoney.*
import kotlinx.android.synthetic.main.layout_buscode_norealname.*
import kotlinx.android.synthetic.main.layout_buscode_qrcode.*
import kotlinx.android.synthetic.main.layout_buscode_qrcode_body.*
import sz.szsmk.citizencard.DaggerApplication
import sz.szsmk.citizencard.R
import sz.szsmk.citizencard.model.network.bean.response.BaseBean
import sz.szsmk.citizencard.model.network.dzbean.res.QrCodeNumberResult
import sz.szsmk.citizencard.mvp.BasePresenter
import sz.szsmk.citizencard.ui.dzsmkfragment.AppBaseFragment
import sz.szsmk.citizencard.ui.newversion.config.Constants
import sz.szsmk.citizencard.ui.newversion.fragment.presenter.BusCodePresenter
import sz.szsmk.citizencard.ui.newversion.fragment.view.BusCodeMvpView
import sz.szsmk.citizencard.util.ACache
import sz.szsmk.citizencard.util.JumpUtils
import sz.szsmk.citizencard.util.PermissionUtil
import sz.szsmk.citizencard.util.QrCodeUtils
import javax.inject.Inject

/**
 *  author : hyt
 *  date : 2020/9/2
 *  description : 乘车码
 */
class BusCodeFragment : AppBaseFragment(), BusCodeMvpView {

    var mVibrator: Vibrator ?=null

    @Inject
    lateinit var busCodePresenter: BusCodePresenter

    override fun initPresenters(): Array<BasePresenter<*>>? {
        return arrayOf(busCodePresenter)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val root = inflater.inflate(R.layout.fragment_buscode, container, false)
        component.inject(this)
        if (ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            PermissionUtil.checkPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE, getResources().getString(R.string.write_permission))
        }
        return root
    }

    override fun getTopTitle() = null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //振动器
        mVibrator = activity?.getSystemService(Service.VIBRATOR_SERVICE) as Vibrator?
    }

    override fun onResume() {
        super.onResume()

        layout_buscode_qrcode_body.visibility = View.GONE
        layout_buscode_norealname.visibility = View.GONE

        busCodePresenter.getOpenId(ACache.get(DaggerApplication.getIns()).getAsString("access_token"))
        //打开震动
        handlerRefreshAndVibrator()
    }

    override fun realNameFalse() {
        //未实名  打开实名界面
        layout_buscode_norealname.visibility = View.VISIBLE
        btn_immediatelyOpen.setOnClickListener {
            //立即开通
            Router.build(Constants.BINDBANKCARDACTIVITY).go(this)
        }
    }

    override fun onGainQrCodeNumber(qrCodeNumberResult: QrCodeNumberResult) {
        layout_buscode_qrcode_body.visibility = View.VISIBLE
        //公交余额查询
        tv_yuechaxun.setOnClickListener {
            val bundle1 = Bundle()
            bundle1.putString("type", "1")
            JumpUtils.jumptoNatvie(requireContext(), "dzsmkuser", 0, bundle1)
        }
        //交易记录
        dzsmk_ccjl.setOnClickListener {
            val bundle1 = Bundle()
            bundle1.putString("type", "0")
            JumpUtils.jumptoNatvie(requireContext(), "dzsmkuser", 0, bundle1)
        }
        //实时公交
        tv_realtiem_bus.setOnClickListener {
            JumpUtils.jump(requireContext(), "BusHomeActivity", 0)
        }

        //1 余额不足
        if(qrCodeNumberResult.resultCode=="1"){
            viewstub_buscode_noenoughmoney.inflate()
            immediatelyRecharge.setOnClickListener {
                //立即充值
                JumpUtils.jumptoNatvie(activity, "RechargeActivity", 0, null)
            }
        }else  {
            //打开二维码页面
            viewstub_buscode_qrcode?.inflate()

            //这里用post 是因为 图片获取不到宽度
            iv_qr_code?.post {
                val qrCode = qrCodeNumberResult.qrCode
                val width: Int = iv_qr_code?.measuredWidth!!
                try {
                    val logo = BitmapFactory.decodeResource(resources, R.drawable.logo)
                    val bitmap = QrCodeUtils.createQRCode(logo, qrCode, width, width / 5)
                    iv_qr_code.setImageBitmap(bitmap)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            tv_showQRagain.setOnClickListener {
                mHandler!!.removeCallbacksAndMessages(null)
                busCodePresenter.getQrNumber()
            }
        }
    }

    override fun onNoQrCodeUsed() {
        showToast("网络异常")
    }

    override fun needRefreshCode(isRefresh: Boolean) {
        needRefreshCode = isRefresh
    }

    override fun onFail(baseBean: BaseBean) {
        showToast(baseBean.message)
    }

    override fun onPause() {
        super.onPause()

        mHandler?.removeCallbacksAndMessages(null)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (null != mVibrator) { //不会去刷新显示的
            mVibrator?.cancel()
            mVibrator = null
        }
    }

    val mHandler =  Handler()
    var needRefreshCode = false
    private val qrImgRefreshTime = 60

    //振动器定时
    override fun handlerRefreshAndVibrator() {
        if (needRefreshCode) { //若需要刷新，则在这里计时
            mHandler?.postDelayed(Runnable {
                //自刷新
                busCodePresenter.getQrNumber()
            }, qrImgRefreshTime * 1000.toLong())
            mHandler?.postDelayed(Runnable {
                handlerVibrator()
            }, qrImgRefreshTime * 1000 - 5000.toLong())
        }
    }

    private fun handlerVibrator() {
        mVibrator?.vibrate(1000) //直接振动1秒

    }

}